#include "AiBox.h"
#include "log/SysLog.h"
#include "config/SystemConfig.h"
#include "db/DBPoll.h"

Box::Box()
{
	m_do_run = true;
}

Box::~Box()
{
}

void Box::Start()
{
	// 载入系统配置
	SystemConfig::get_mutable_instance().LoadConfig();
	LOG_INFO("load system config success.");

	// 数据库初始化
	DBConf dbConf = SystemConfig::get_mutable_instance().GetDBConf();
	DBPoll::get_mutable_instance().Init(5,
		dbConf.GetDbType(), dbConf.GetIp(),
		dbConf.GetPort(), dbConf.GetUser(),
		dbConf.GetPassword(), dbConf.GetDbName());
	LOG_INFO("init system tables success, db type:{} (0 is mysql).", dbConf.GetDbType());

	// 创建数据表
	DBPoll::get_mutable_instance().CreateTables();

	// 初始化测试数据
	// DBPoll::get_mutable_instance().InitDefaultData();

	// 启动AI引擎
	m_engine = std::make_shared<Engine>();
	if (m_engine)
	{
		m_engine->Start();
	}
	LOG_INFO("start ai engine success.");

	// 启动AI控制器
	m_controller = std::make_shared<AiMonitor>();
	if (m_controller)
	{
		m_controller->Start();
	}
	LOG_INFO("start ai controller success.");

	// 启动Http服务器
	LocalConf localConf = SystemConfig::get_mutable_instance().GetLocalConf();
	m_http_server = std::make_shared<HttpServer>();
	m_http_server->Start(localConf.GetHttpPort());

	// 启动文件清理
	m_fileClear = std::make_shared<FileClear>();
	if (m_fileClear)
	{
		m_fileClear->Start();
	}
	LOG_INFO("start file clear success.");

	// 启动网络套接口
	m_socket_client = std::make_shared<WebsocektClient>();
	if (m_socket_client)
	{
		m_socket_client->Start();
	}

	// 启动服务
	m_do_run = true;
}

void Box::Stop()
{
	// 停止套接口服务
	LOG_INFO("stop socket server..");
	if (m_socket_client)
	{
		m_socket_client->Stop();
		m_socket_client.reset();
		m_socket_client = nullptr;
	}

	// 停止http服务
	LOG_INFO("stop http server..");
	if (m_http_server)
	{
		m_http_server->Stop();
		m_http_server.reset();
		m_http_server = nullptr;
	}

	// 停止AI控制器
	LOG_INFO("stop ai controller..");
	if (m_controller)
	{
		m_controller->Stop();
		m_controller.reset();
		m_controller = nullptr;
	}

	// 停止AI引擎
	LOG_INFO("stop ai engine..");
	if (m_engine)
	{
		m_engine->Stop();
		m_engine.reset();
		m_engine = nullptr;
	}

	// 停止文件清理
	LOG_INFO("stop file clear..");
	if (m_fileClear)
	{
		m_fileClear->Stop();
		m_fileClear.reset();
		m_fileClear = nullptr;
	}

	// 关闭数据连接
	LOG_INFO("close database pool..");
	DBPoll::get_mutable_instance().Close();

	// 停止服务
	m_do_run = false;
	LOG_INFO("stop box success!");
}

bool& Box::IsRun()
{
	return m_do_run;
}

HttpServerPtr Box::GetHttpServer()
{
	return m_http_server;
}

WebsocektClientPtr Box::GetSocketClient()
{
	return m_socket_client;
}

EnginePtr Box::GetEngine()
{
	return m_engine;
}

AiMonitorPtr Box::GetAiMonitor()
{
	return m_controller;
}

FileClearPtr Box::GetFileClear()
{
	return m_fileClear;
}